package com.platform.license.service;

import com.platform.license.MachineUtils;
import de.schlichtherle.license.*;
import de.schlichtherle.xml.GenericCertificate;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.NonNull;
import org.springframework.util.StringUtils;

import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.Objects;

/**
 * Description: 自定义LicenseManager，用于增加额外的服务器硬件信息校验
 *
 * @author libinal Created on 2019/9/22
 */
public class LicManager extends LicenseManager {

    private static ApplicationContext context;

    /**
     * XML编码
     */
    private static final String XML_CHARSET = "UTF-8";

    /**
     * 默认 BUFFER SIZE
     */
    private static final int DEFAULT_BUFFER_SIZE = 8 * 1024;

    public LicManager(LicenseParam param) {
        super(param);
    }

    @Override
    protected synchronized byte[] create(LicenseContent content, LicenseNotary notary) throws Exception {
        initialize(content);
        this.validateCreate(content);
        final GenericCertificate certificate = notary.sign(content);
        return getPrivacyGuard().cert2key(certificate);
    }

    /**
     * 重写install方法，其中validate方法调用本类中的validate方法，校验IP地址、Mac地址等其他信息。
     */
    @Override
    protected synchronized LicenseContent install(byte[] key, LicenseNotary notary) throws Exception {
        final GenericCertificate certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded());
        this.validate(content);
        setLicenseKey(key);
        setCertificate(certificate);
        return content;
    }

    /**
     * 重写verify方法，调用本类中的validate方法，校验IP地址=Mac地址等其他信息。
     */
    @Override
    protected synchronized LicenseContent verify(LicenseNotary notary) throws Exception {
        GenericCertificate certificate;
        final byte[] key = getLicenseKey();
        if (null == key) {
            throw new NoLicenseInstalledException(getLicenseParam().getSubject());
        }
        certificate = getPrivacyGuard().key2cert(key);
        notary.verify(certificate);
        final LicenseContent content = (LicenseContent) this.load(certificate.getEncoded());
        this.validate(content);
        setCertificate(certificate);
        return content;
    }

    /**
     * 校验生成证书的参数信息
     *
     * @param content 证书正文
     */
    private synchronized void validateCreate(LicenseContent content) throws LicenseContentException {
        final Date now = new Date();
        final Date notBefore = content.getNotBefore();
        final Date notAfter = content.getNotAfter();
        if (null != notAfter && now.after(notAfter)) {
            throw new LicenseContentException("证书失效时间不能早于当前时间");
        }
        if (null != notBefore && null != notAfter && notAfter.before(notBefore)) {
            throw new LicenseContentException("证书生效时间不能晚于证书失效时间");
        }
        final String consumerType = content.getConsumerType();
        if (null == consumerType) {
            throw new LicenseContentException("用户类型不能为空");
        }
    }

    private Object load(String encode) {
        try (
                BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(encode.getBytes(XML_CHARSET)));
                XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(inputStream, DEFAULT_BUFFER_SIZE), null, null)
        ) {
            return decoder.readObject();
        } catch (Exception e) {
            throw new RuntimeException("读取序列号文件失败: " + e.getMessage());
        }
    }

    /**
     * 重写validate方法，增加IP地址、Mac地址等其他信息校验
     */
    @Override
    protected synchronized void validate(final LicenseContent content) throws LicenseContentException {
        // 1. 首先调用父类的validate方法
        super.validate(content);

        // 2.然后校验自定义的License参数。License中可被允许的参数
        String expected = (String) content.getExtra();
        // 当前服务器真实的参数信息
        String serial = getServerInfo();

        if (expected != null && !StringUtils.isEmpty(serial)) {
            // 校验序列号
            if (checkSerials(expected, serial)) {
                throw new LicenseContentException("当前服务器未授权");
            }
        } else {
            throw new LicenseContentException("当前服务器未授权");
        }

    }

    /**
     * 校验序列号
     *
     * @param expectedSerial 允许的序列号
     * @param serverSerial   服务器真实序列号
     * @return Boolean
     */
    private boolean checkSerials(String expectedSerial, String serverSerial) {
        if (StringUtils.isEmpty(expectedSerial)) {
            return false;
        }
        if (StringUtils.isEmpty(serverSerial)) {
            return true;
        }
        return !expectedSerial.equals(serverSerial);
    }

    /**
     * 获取服务序列号
     *
     * @return 序列号
     */
    private String getServerInfo() {
        return MachineUtils.generate();
    }

    public static void setApplicationContext(@NonNull ApplicationContext applicationContext) {
        if (Objects.isNull(LicManager.context)) {
            LicManager.context = applicationContext;
        }
    }
}
